/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.linkwithweb.products.swiftui.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.linkwithweb.products.swiftui.dao.impl.SwiftUIDBHelper;
import com.linkwithweb.products.swiftui.service.PlatformService;
import com.linkwithweb.products.swiftui.ui.model.JSTreeAttribute;
import com.linkwithweb.products.swiftui.ui.model.JSTreeNode;
import com.linkwithweb.products.swiftui.ui.model.JSTreeResponse;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class JSTreeController extends AbstractController {

	private static String DB_MODE = "MYSQL";
	private boolean isFrameworkJDBCTemplate = false;
	@Autowired
	@Qualifier("platformService")
	private PlatformService platformService;

	/**
	 * Constructor
	 */
	public JSTreeController() {
		if (StringUtils.equalsIgnoreCase(DB_MODE, "MYSQL")) {
			isFrameworkJDBCTemplate = false;
		}
	}

	@RequestMapping("/jsTreeConfig")
	public ModelAndView jsTreeConfig(@RequestParam(value = "gridName") String gridName) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		return new ModelAndView("jsTree/jsTreeDefinition", paramMap);
	}

	/**
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/jsTreeEdit")
	public ModelAndView jsTreeEdit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		String gridName = httpServletRequest.getParameter("gridName");
		String operation = httpServletRequest.getParameter("oper");

		Map<String, Object> paramMap = new HashMap<String, Object>();

		return new ModelAndView("blank", paramMap);
	}

	/**
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/jsTreeData")
	public @ResponseBody
	Object jsTreeData(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		String treeName = httpServletRequest.getParameter("treeName");
		String id = httpServletRequest.getParameter("id");
		String operation = httpServletRequest.getParameter("operation");
		String copy = httpServletRequest.getParameter("copy");
		String ref = httpServletRequest.getParameter("ref");
		String title = httpServletRequest.getParameter("title");
		String type = httpServletRequest.getParameter("type");

		List<JSTreeNode> treeData = new ArrayList<JSTreeNode>();

		JSTreeNode jsTreeNode = new JSTreeNode();
		JSTreeAttribute attribute = new JSTreeAttribute();

		String parentNodeId = "-1";

		if (StringUtils.isEmpty(id)) {
			parentNodeId = "-1";
		} else{
			parentNodeId = id;
		}
		if (id.equalsIgnoreCase("1")) {
			parentNodeId = "-1";
		}

		if (StringUtils.equalsIgnoreCase(operation, "get_children")) {
			StringBuffer querySQL = new StringBuffer();

			querySQL.append("SELECT * FROM FRM_MENU WHERE PARENT_MENU_ID = '" + parentNodeId).append(
					"' AND MENU_TYPE = 'TREE' ORDER BY MENU_ORDER ASC");

			List<Map<String, Object>> dbTreeData = SwiftUIDBHelper.getInstance().getJdbcTemplate("jdbcTemplate")
					.queryForList(querySQL.toString());

			for (Map<String, Object> treeNodeRow : dbTreeData) {
				jsTreeNode = new JSTreeNode();
				attribute = new JSTreeAttribute();
				jsTreeNode.setData((String) treeNodeRow.get("MENU_LABEL"));
				
				String parentId = (String)treeNodeRow.get("PARENT_MENU_ID");
				String state = "";
				String rel = "";
				if(parentId.equalsIgnoreCase("-1")){
					state = "closed";
					rel = "folder";
				}
				
				jsTreeNode.setState(state);
				attribute.setId((String) treeNodeRow.get("MENU_ID"));
				attribute.setRel(rel);
				jsTreeNode.setAttr(attribute);
				treeData.add(jsTreeNode);
			}

		} else if (StringUtils.equalsIgnoreCase(operation, "move_node")) {
			StringBuffer querySQL = new StringBuffer();
			querySQL.append("UPDATE FRM_TREE_STRUCTURE").append(" SET PARENT_NODE_ID  = " + ref).append(
					" WHERE NODE_ID = '").append(parentNodeId).append("' AND NODE_TYPE = '").append(treeName).append(
					"'");
			SwiftUIDBHelper.getInstance().getJdbcTemplate("jdbcTemplate").update(querySQL.toString());
			JSTreeResponse response = new JSTreeResponse();
			response.setId(id);
			response.setStatus("1");
			return response;
		} else if (StringUtils.equalsIgnoreCase(operation, "create_node")) {
			StringBuffer querySQL = new StringBuffer();
			int maxNodeId = SwiftUIDBHelper.getInstance().getJdbcTemplate("jdbcTemplate").queryForInt(
					"SELECT MAX(NODE_ID) FROM FRM_TREE_STRUCTURE");
			maxNodeId = maxNodeId + 1;
			/*if (parentNodeId == 2) {

				*//**
				 * Send Resposne Back
				 *//*
				JSTreeResponse response = new JSTreeResponse();
				response.setId(id);
				response.setStatus("0");
				response.setErrorMessage("Wait till Request is authorized to see the Node");
				return response;
			}*/

			querySQL
					.append("INSERT INTO FRM_TREE_STRUCTURE(NODE_ID,NODE_TYPE,NODE_DATA,NODE_REL,PARENT_NODE_ID,NODE_ORDER) VALUES (?,?,?,?,?,?)");

			List arguments = new ArrayList();
			arguments.add(maxNodeId);
			arguments.add(treeName);
			arguments.add(title);
			if (StringUtils.isNotBlank(type)) {
				arguments.add(type);
			} else {
				arguments.add("default");
			}
			arguments.add(parentNodeId);
			arguments.add(maxNodeId);

			SwiftUIDBHelper.getInstance().getJdbcTemplate("jdbcTemplate").update(querySQL.toString(),
					arguments.toArray());
			JSTreeResponse response = new JSTreeResponse();
			response.setId(id);
			response.setStatus("1");
			return response;
		} else if (StringUtils.equalsIgnoreCase(operation, "rename_node")) {
			StringBuffer querySQL = new StringBuffer();
			querySQL.append("UPDATE FRM_TREE_STRUCTURE").append(" SET NODE_DATA  = '" + title).append(
					"' WHERE NODE_ID = '").append(parentNodeId).append("' AND NODE_TYPE = '").append(treeName).append(
					"'");
			SwiftUIDBHelper.getInstance().getJdbcTemplate("jdbcTemplate").update(querySQL.toString());
			JSTreeResponse response = new JSTreeResponse();
			response.setId(id);
			response.setStatus("1");
			return response;
		} else if (StringUtils.equalsIgnoreCase(operation, "remove_node")) {
			StringBuffer querySQL = new StringBuffer();
			querySQL.append("DELETE FROM FRM_TREE_STRUCTURE").append(" WHERE NODE_ID  = '" + id).append("'");
			SwiftUIDBHelper.getInstance().getJdbcTemplate("jdbcTemplate").update(querySQL.toString());
			JSTreeResponse response = new JSTreeResponse();
			response.setId(id);
			response.setStatus("1");
			return response;
		}

		return treeData;
	}

}
